package org.softwarepoets.emf.ecore.editor.extensions;

import org.eclipse.emf.ecore.EAnnotation;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EOperation;
import org.eclipse.emf.ecore.EcoreFactory;
import org.eclipse.emf.ecore.EcorePackage;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.dialogs.IInputValidator;
import org.eclipse.jface.dialogs.InputDialog;
import org.eclipse.ui.PlatformUI;

public class CreateEOperationWithAnnotation extends
		AbstractExtensionAction {

	public CreateEOperationWithAnnotation() {
		super(EClass.class);
	}

	@Override
	public void run(IAction action) {
		InputDialog dialog = new InputDialog(
				PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(),
				"Enter Validator Operation name",
				"Enter the name of the operation without parameters using valid java naming conventions.",
				"", new JavaNamingValidator());

		if (dialog.open() == InputDialog.OK) {
			EClass object = (EClass) element;
			String name = dialog.getValue();
			EOperation eOper = EcoreFactory.eINSTANCE.createEOperation();
			eOper.setName(name);
			if (name.startsWith("is") || name.startsWith("has")) {
				eOper.setEType(EcorePackage.Literals.EBOOLEAN);
			}
			object.getEOperations().add(eOper);
			EAnnotation eAnnotation = EcoreFactory.eINSTANCE
					.createEAnnotation();
			eOper.getEAnnotations().add(eAnnotation);
			eAnnotation.setSource("http://www.eclipse.org/emf/2002/GenModel");
			eAnnotation.getDetails().put("body", "");
		}
	}

}

class JavaNamingValidator implements IInputValidator {
	public String isValid(String newText) {
		if (newText == null || newText.length() == 0)
			return "You must enter an operation name.";
		// maybe include an elaborate regular expression here...
		// otherwise ok
		if (!newText.matches("[a-zA-Z_0-9]+"))
			return "You must enter a valid java idenitifier.";
		
		return null;
	}
}
